package com.itheima.servletlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/listStudentservlet")
public class ListStudentservlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过缓冲字符输入流获取(F:\\GGBBSS.txt)文本当中的数据
        BufferedReader br = new BufferedReader(new FileReader("F:\\GGBBSS.txt"));
        //创建学生泛型集合
        ArrayList<Student> list = new ArrayList<>();
        //变量名
        String line;
        //遍历集合
        while ((line = br.readLine()) != null) {
            //创建学生对象
            Student stu = new Student();
            //通过逗号切割,变为数组
            String[] arr = line.split(",");
            //把数组中的三个索引添加到学生对象中,集合添加学生对象
            stu.setUsername(arr[0]);
            stu.setAge(Integer.parseInt(arr[1]));
            stu.setScore(Integer.parseInt(arr[2]));
            list.add(stu);
        }
        //设置编码格式
        resp.setContentType("text/html;charset=UTF-8");
        //把集合对象添加到会话域中
        req.getSession().setAttribute("Students", list);
        //重定向到(listStudent)页面
        resp.sendRedirect("/listStudent.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
